import wtforms
from wtforms.validators import InputRequired, Email, Length, EqualTo, Regexp
from models import UserModel, EmailCaptchaModel
from exts import db


class RegisterForm(wtforms.Form):
    username = wtforms.StringField('Username', validators=[InputRequired()])
    password = wtforms.PasswordField('Password', validators=[InputRequired(),
                                                             Regexp(r'^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$',
                                                                    message="至少8位，包含字母和数字")])
    verify_password = wtforms.PasswordField('Verify_password',
                                            validators=[InputRequired(), EqualTo('password', message="两次密码不一致")])
    email = wtforms.StringField('Email', validators=[InputRequired(), Email(message="邮箱格式不正确")])
    captcha = wtforms.StringField('Captcha',
                                  validators=[InputRequired(), Length(min=6, max=6, message="验证码格式不正确")])

    def validate_email(self, field):  # 自定义验证器
        email = field.data
        if UserModel.query.filter_by(email=email).first():
            raise wtforms.ValidationError('邮箱已被注册')

    def validate_captcha(self, field):
        captcha = field.data
        email = self.email.data
        captcha_model = EmailCaptchaModel.query.filter_by(email=email, captcha=captcha).first()
        if not captcha_model:
            raise wtforms.ValidationError('验证码不存在')
        elif captcha.lower() != captcha_model.captcha.lower():
            raise wtforms.ValidationError('验证码不正确')
        else:
            db.session.delete(captcha_model)  # 验证码只能使用一次
            db.session.commit()


class LoginForm(wtforms.Form):
    password = wtforms.PasswordField('Password', validators=[InputRequired()])
    username = wtforms.StringField('Username', validators=[InputRequired()])


class QuestionForm(wtforms.Form):
    title = wtforms.StringField('Title', validators=[InputRequired(), Length(min=2, max=20, message="标题长度为2-20")])
    content = wtforms.StringField('Content', validators=[InputRequired(), Length(min=2)])


class AnswerForm(wtforms.Form):
    content = wtforms.StringField('Content', validators=[InputRequired(), Length(min=2)])
    question_id = wtforms.IntegerField('Question_id', validators=[InputRequired()])
